#include "app_mqtt.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <MQTTClient.h> // https://github.com/eclipse/paho.mqtt.c
#include <assert.h>
#include "log/log.h"

static MQTTClient client;                                                           // MQTT客户端
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; // 连接选项配置
static MQTTClient_message pubmsg = MQTTClient_message_initializer;                  // 发布消息配置
static MQTTClient_deliveryToken deliveredtoken;                                     // 消息交付令牌

static int (*recv_callback)(void *data, int len);

// 发送消息完成的回调
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("Message with token value %d delivery confirmed\n", dt);
    deliveredtoken = dt;
}

// 收到消息的回调
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    log_debug("收到消息， topic:%s, payload: %s, len: %d", topicName, (char*)message->payload, message->payloadlen);

    int result = recv_callback(message->payload, message->payloadlen) == 0 ? 1 : 0;
    
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);

    return result; // 成功返回1，失败返回0
}

// 连接断开回调
void connlost(void *context, char *cause)
{
    log_fatal("Connection lost, cause: %s", cause);
    exit(EXIT_FAILURE);
}

int app_mqtt_init()
{
    int rc;
    // 创建客户端
    if ((rc = MQTTClient_create(&client, ADDRESS, CLIENTID,
                                MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to create client, return code %d\n", rc);
        return -1;
    }

    // 设置回调
     if ((rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to set callbacks, return code %d\n", rc);
        return -1;
    }

    // 连接服务器
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        log_warn("Failed to connect, return code %d\n", rc);
        return -1;
    }
    log_debug("MQTT连接成功");
    return 0;
}

void app_mqtt_close()
{
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}

int app_mqtt_send(void *data, int len)
{
    MQTTClient_deliveryToken token; // 消息交付令牌
    pubmsg.payload = data;
    pubmsg.payloadlen = len;
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    deliveredtoken = 0;
    int rc;
    if ((rc = MQTTClient_publishMessage(client, TOPIC_PUSH, &pubmsg, &token)) != MQTTCLIENT_SUCCESS)
    {
        log_warn("Failed to publish message, return code %d\n", rc);
        return -1;
    }
    log_debug("Waiting for publication of %s", TOPIC_PUSH);

    return 0;
}

void app_mqtt_registerRecvCallback(int (*callback)(void *, int))
{
    recv_callback = callback;
}
